package cn.itcast.bos.action.base;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.action.common.BaseAction;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.IFixedAreaService;
@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea>{

	private static final long serialVersionUID = 8982588473272078286L;
	
	@Autowired
	private IFixedAreaService fixedAreaService;
	
	/**
	 * 保存定区
	 * @return
	 */
	@Action(value="fiexarea_save",results={@Result(name="success",location="/pages/base/fixed_area.html",type="redirect")})
	public String fixedAreaSave(){
		fixedAreaService.save(model);
		return SUCCESS;
	}
	
	/**
	 * 分页显示定取
	 */
	@Action(value="fixedarea_pagequery",results={@Result(name="none",type="json")})
	public String fixedAreaPageQuery(){
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			// 构建查询条件
			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				// ID条件
				if (StringUtils.isNotBlank(model.getId())) {
					Predicate fixedAreaIdWhere = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(fixedAreaIdWhere);
				}
				// 公司条件
				if (StringUtils.isNotBlank(model.getCompany())) {
					Predicate fixedAreaCompanyWhere = cb.like(root.get("company").as(String.class), "%"+model.getCompany()+"%");
					list.add(fixedAreaCompanyWhere);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Pageable pageable = new PageRequest(page-1, rows);
		Page<FixedArea> fiexAreas = fixedAreaService.findAll(specification, pageable);
		pushPageDateToValueStack(fiexAreas);
		return NONE;
	}
}
